package bigdata;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.*;

import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JList;

import backtype.storm.utils.Utils;

import java.awt.Font;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.Locale;
import java.util.Vector;

public class GuiTest {

	private JFrame frmBigdataSimulationProgram;
	private DefaultStyledDocument doc;
	private JTextArea textArea;
	private JButton btnStart;
	private JButton btnViewSimulation;
	private DefaultTableModel model;
	private boolean simulationWindowIsVisible = false;
	private JLabel lblSpoutDelayTime;
	public JTextField delayTime;
	private JButton btnChoose;
	
	public JLabel lblSearch;
	public JLabel lblPageViews;
	
	// Create a file chooser
	final JFileChooser fc = new JFileChooser();

	/**
	 * Launch the application.
	 */

	/**
	 * Create the application.
	 */
	public GuiTest() {
		initialize();
		frmBigdataSimulationProgram.setVisible(true);

	}

	final Runnable doHelloWorld = new Runnable() {
		public void run() {
			textArea.repaint();
			textArea.revalidate();
			textArea.validate();
		}
	};
	private JTable table;

	public void setVisitListFromDb(VisitData[] visitors) {
		model.setRowCount(0);
		for (int i = 0; i < visitors.length; i++) {
			addLineToList(visitors[i]);
		}
	}

	public void addLineToList(VisitData visitor) {
		model.addRow(new Object[] { visitor.visitId, visitor.type, visitor.getScore(),visitor.getRate(),  visitor.browser });
	
	}

	public void addStringToLog(String newLine) {
		// Create and add the style
		// Create the StyleContext, the document and the pane

		textArea.append(newLine + "\n");
		textArea.setCaretPosition(textArea.getDocument().getLength());
		textArea.validate();
		textArea.repaint();
		// try {
		// SwingUtilities.invokeAndWait(doHelloWorld);
		// } catch (InvocationTargetException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// } catch (InterruptedException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {

		frmBigdataSimulationProgram = new JFrame();
		frmBigdataSimulationProgram.getContentPane().setBackground(Color.WHITE);
		frmBigdataSimulationProgram.setBounds(100, 100, 830, 514);
		frmBigdataSimulationProgram.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frmBigdataSimulationProgram.getContentPane().setLayout(null);

		btnStart = new JButton("START");
		btnStart.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				if (isInteger(delayTime.getText().toString())) {
					if (!SimulationMain.logPath.equals("")) {
						btnStart.setEnabled(false);
						Thread stormThread = new Thread() {
							public void run() {
								synchronized (this) {
									// ExclamationTopology.runStorm();
	
									RunStorm.run();
								}
							}
						};
	
						Thread refreshThread = new Thread() {
							public void run() {
								synchronized (this) {
									while (true) {
										Utils.sleep(1000);
	
										SimulationMain.gui.setVisitListFromDb(SqlDB.getCustomersList());
									}
								}
							}
						};
						stormThread.start();
						refreshThread.start();
					}
					else
						SimulationMain.gui.addStringToLog("Error: please choose log file!");
				}
				else
					SimulationMain.gui.addStringToLog("Error: please choose delay number!");

			}

		});

		btnViewSimulation = new JButton("view simulation");
		// btnViewSimulation.setEnabled(true);
		btnViewSimulation.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				if (!simulationWindowIsVisible) {
					SimulationMain.simuFrame.setVisible(true);
					simulationWindowIsVisible = true;
				} else {
					SimulationMain.simuFrame.setVisible(false);
					simulationWindowIsVisible = false;
				}
			}
		});

		btnStart.setBounds(334, 58, 105, 23);
		frmBigdataSimulationProgram.getContentPane().add(btnStart);

		JLabel lblLog = new JLabel("Log:");
		lblLog.setBounds(10, 330, 46, 14);
		frmBigdataSimulationProgram.getContentPane().add(lblLog);

		StyleContext sc = new StyleContext();
		doc = new DefaultStyledDocument(sc);

		JLabel lblNewLabel = new JLabel("BigData Simulation");
		lblNewLabel.setFont(new Font("Verdana", Font.BOLD, 23));
		lblNewLabel.setBounds(264, 11, 255, 36);
		frmBigdataSimulationProgram.getContentPane().add(lblNewLabel);

		textArea = new JTextArea();
		textArea.setEditable(false);

		DefaultCaret caret = (DefaultCaret) textArea.getCaret();
		caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

		JScrollPane scroll = new JScrollPane(textArea);
		scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scroll.setBounds(10, 355, 582, 109);

		frmBigdataSimulationProgram.getContentPane().add(scroll);

		JLabel lblNewLabel_1 = new JLabel("Top Visitors");
		lblNewLabel_1.setBounds(10, 74, 79, 14);
		frmBigdataSimulationProgram.getContentPane().add(lblNewLabel_1);

		model = new DefaultTableModel();
		JTable table = new JTable(model);

		// Create a couple of columns
		model.addColumn("Customer id");
		model.addColumn("User type");
		model.addColumn("Score");
		model.addColumn("Used chat before n.");
		model.addColumn("Time on page");
		
		table.setRowSelectionAllowed(false);
		table.setFillsViewportHeight(true);

		JScrollPane tableScroll = new JScrollPane(table);
		tableScroll.setBounds(10, 87, 794, 240);
		frmBigdataSimulationProgram.getContentPane().add(tableScroll);

		btnViewSimulation.setBounds(689, 58, 115, 23);
		frmBigdataSimulationProgram.getContentPane().add(btnViewSimulation);

		lblSpoutDelayTime = new JLabel("Spout delay time:");
		lblSpoutDelayTime.setBounds(10, 44, 89, 14);
		frmBigdataSimulationProgram.getContentPane().add(lblSpoutDelayTime);

		delayTime = new JTextField();
		delayTime.setText("1000");
		delayTime.setBounds(98, 41, 86, 20);
		frmBigdataSimulationProgram.getContentPane().add(delayTime);
		delayTime.setColumns(5);

		btnChoose = new JButton("Choose...");
		btnChoose.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// In response to a button click:
				int returnVal = fc.showOpenDialog(frmBigdataSimulationProgram);

				if (returnVal == JFileChooser.APPROVE_OPTION) {
					File file = fc.getSelectedFile();
					// This is where a real application would open the file.
					SimulationMain.logPath = file.getAbsolutePath();
					btnChoose.setText(file.getName());
					System.out.println("Opening: " + file.getAbsolutePath());
				} else {
					System.out.println("Open command cancelled by user.");
				}
			}
		});
		btnChoose.setBounds(98, 11, 89, 23);
		frmBigdataSimulationProgram.getContentPane().add(btnChoose);

		JLabel lblLogFile = new JLabel("Log file:");
		lblLogFile.setBounds(10, 15, 46, 14);
		frmBigdataSimulationProgram.getContentPane().add(lblLogFile);
		
		JLabel lblAvgSiteSearches = new JLabel("AVG site searches:");
		lblAvgSiteSearches.setBounds(602, 361, 105, 14);
		frmBigdataSimulationProgram.getContentPane().add(lblAvgSiteSearches);
		
		JLabel lblAvgSitePage = new JLabel("AVG site page views:");
		lblAvgSitePage.setBounds(602, 386, 105, 14);
		frmBigdataSimulationProgram.getContentPane().add(lblAvgSitePage);
		
		lblSearch = new JLabel("0");
		lblSearch.setBounds(726, 361, 46, 14);
		frmBigdataSimulationProgram.getContentPane().add(lblSearch);
		
		lblPageViews = new JLabel("0");
		lblPageViews.setBounds(726, 386, 46, 14);
		frmBigdataSimulationProgram.getContentPane().add(lblPageViews);

	}

	public static boolean isInteger(String s) {
		try {
			Integer.parseInt(s);
		} catch (NumberFormatException e) {
			return false;
		}
		// only got here if we didn't return false
		return true;
	}
}
